'use strict'

gulp = require 'gulp'
_ = require 'lodash'
gutil = require 'gutil'

ngmin = require 'gulp-ngmin'
coffee = require 'gulp-coffee'
concat = require 'gulp-concat'
uglify = require 'gulp-uglify'
assets = require 'gulp-assets'
filter = require 'gulp-filter'
minifyCSS = require 'gulp-minify-css'
minifyHTML = require 'gulp-minify-html'
htmlReplace = require 'gulp-html-replace'
sourcemaps = require 'gulp-sourcemaps'
path =
  coffee:
    src: './app/scripts/**/*.coffee'
    dest: './app/scripts/'
  coffeeMap:
    src: ['controllers', 'directives', 'filters', 'services', '']

gulp.task 'coffeeMap', () ->
  _.each path.coffeeMap.src, (e) ->
    src = "./app/scripts/#{e}/*.coffee"
    gulp.src src
      .pipe sourcemaps.init()
      .pipe coffee().on 'error', gutil.log
      .pipe sourcemaps.write "./"
      .pipe gulp.dest "./app/js/" + e

gulp.task 'coffee', () ->
  gulp.src path.coffee.src
    .pipe coffee()
    .pipe gulp.dest path.coffee.dest

gulp.task 'watch', () ->
  gulp.watch path.coffee.src, ['coffeeMap']

gulp.task 'buildScript', ['coffee'], () ->

  gulp.src("./app/index.html")
    .pipe(assets({
        js: yes
        css: no
    }))
    .pipe(filter('js/**/*.js'))
    .pipe(ngmin())
    .pipe(uglify())
    .pipe(concat('app.js'))
    .pipe(gulp.dest('./dist/js/'))

gulp.task 'buildBower', () ->
  gulp.src("./app/index.html")
    .pipe(assets({
        js: yes
        css: no
    }))
    .pipe(filter('bower_components/**/*.js'))
    .pipe(uglify())
    .pipe(concat('vendor.js'))
    .pipe(gulp.dest('./dist/js/'))

gulp.task 'buildCss', () ->

  gulp.src("./app/index.html")
    .pipe(assets({
        js: no
        css: yes
    }))
    .pipe(minifyCSS({keepBreaks:true}))
    .pipe(concat('style.css'))
    .pipe(gulp.dest('./dist/css/'))

gulp.task 'buildResource', () ->
  gulp.src('./app/bower_components/bootstrap/dist/fonts/*')
    .pipe(gulp.dest('./dist/fonts/'))

  gulp.src('./app/img/*')
    .pipe(gulp.dest('./dist/img/'))

gulp.task 'buildHtml', () ->
  gulp.src './app/views/**/*.html'
  .pipe minifyHTML
      empty: yes
      spare: yes
      quotes: yes
      conditionals: yes
      comments:yes
  .pipe gulp.dest './dist/views/'
  i = Math.round Math.random() * 1000000
  i = '?' + i
  gulp.src './app/index.html'
  .pipe htmlReplace
        jsApp: 'js/app.js' + i
        jsVendor: 'js/vendor.js' + i
        css: 'css/style.css' + i
  .pipe gulp.dest './dist/'



gulp.task 'default', ['coffeeMap', 'watch']

gulp.task 'build', ['buildScript', 'buildBower', 'buildCss', 'buildHtml', 'buildResource']

